package com.iye.puretennis.custom;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.iye.puretennis.R;
import com.iye.puretennis.domain.ListItem;

import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/9
 * Time: 16:13
 */
public class ListItemAdapter extends BaseAdapter {

    protected LinkedList<ListItem> items = new LinkedList<ListItem>();

    protected int resource;//数据绑定在哪个资源界面上

    protected LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象

    protected ViewCache viewCache;

    public ListItemAdapter(LayoutInflater inflater, int resource, LinkedList<ListItem> items) {
        this.resource = resource;
        this.inflater = inflater;
        this.items = items;
    }


    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int i) {
        return items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        initial(i,view);

        return view;
    }

    public void removeItem(int position) {
        items.remove(position);
        this.notifyDataSetChanged();
    }

    protected View initial(int i, View view) {
        HuaWenHuPoTextView labelView,numberView;

        if (view == null) {//为第一页显示,创建view对象
            view = inflater.inflate(resource, null);//null没有根元素

            labelView = (HuaWenHuPoTextView) view.findViewById(R.id.item_label);

            numberView = (HuaWenHuPoTextView) view.findViewById(R.id.request_number);

            viewCache = new ViewCache(labelView,numberView);

            view.setTag(viewCache);
        } else {

            viewCache = (ViewCache) view.getTag();

            labelView = viewCache.nameView;

        }

        ListItem listItem = items.get(i);

        labelView.setText(listItem.getName());

        return view;

    }

    /**
     * 该类用于缓存View对象,第一页的时候进行创建,第二页数据的时候使用缓存
     * 这种写法的另一个优点是代码数量少占用内存小,另一种是set/get方法
     */
    protected final class ViewCache {
        public HuaWenHuPoTextView nameView;
        public HuaWenHuPoTextView numberView;

        public ViewCache(HuaWenHuPoTextView nameView,HuaWenHuPoTextView numberView) {
            this.nameView = nameView;
            this.numberView = numberView;
        }
    }


}
